package com.weetop.cfw.mine.activity

import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import com.blankj.utilcode.util.ActivityUtils
import com.kongzue.dialog.v3.MessageDialog
import com.weetop.cfw.R
import com.weetop.cfw.base.ui.activity.CommonBaseActivity
import kotlinx.android.synthetic.main.activity_personal_information.*
import com.kongzue.dialog.v3.BottomMenu
import com.weetop.cfw.utils.PictureSelectorUtils
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import android.content.Intent
import android.app.Activity
import android.text.Editable
import com.blankj.utilcode.util.ColorUtils
import com.blankj.utilcode.util.LogUtils
import com.weetop.cfw.base.presenter.imp.PersonalInformationPresenterImp
import com.weetop.cfw.base.view.PersonalInformationView
import com.weetop.cfw.bean.PersonalInfoBean
import com.weetop.cfw.constants.UrlConstants
import com.weetop.cfw.register.UpdatePasswordActivity
import com.weetop.cfw.utils.GlideUtils


/**
 * 个人资料界面
 */
class PersonalInformationActivity : CommonBaseActivity(),View.OnClickListener,PersonalInformationView {

    private lateinit var personalInformationPresenterImp: PersonalInformationPresenterImp

    //用户头像
    private var userHeadImg = ""
    //用户昵称
    private var nickName = ""
    //用户真实姓名
    private var realName = ""
    //用户性别
    private var sex = ""
    //用户电子邮箱
    private var userEmail = ""
    //用户注册公司名称
    private var userCompanyName = ""
    //用户名
    private var username = ""
    //用户的新头像地址
    private var userNewHeadImg = ""

    override fun onClick(p0: View?) {
        when(p0?.id){
            R.id.imagePersonInfoBack -> tipUserSaveInfo()
            R.id.superTextHeadImg -> showChooseHeadImgBottomSheet()
            R.id.relativeUserSex -> showChooseSexBottomSheet()
            R.id.imageUpdatePasswordRight,R.id.editUpdatePassword,R.id.textUpdatePasswordLabel,R.id.imageUpdatePasswordLogo -> ActivityUtils.startActivity(UpdatePasswordActivity::class.java)
        }
    }

    override fun getLayoutId() = R.layout.activity_personal_information

    override fun initView(savedInstanceState: Bundle?) {
        personalInformationPresenterImp = PersonalInformationPresenterImp()
        personalInformationPresenterImp.attachView(this)

       setViewsOnClickListener(this,imagePersonInfoBack,superTextHeadImg,relativeUserSex,imageUpdatePasswordLogo,textUpdatePasswordLabel,editUpdatePassword,imageUpdatePasswordRight)
    }

    override fun initData(savedInstanceState: Bundle?) {
        personalInformationPresenterImp.getPersonalInfoData(this)
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if(keyCode == KeyEvent.KEYCODE_BACK){
            tipUserSaveInfo()
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    override fun onDestroy() {
        super.onDestroy()
        personalInformationPresenterImp.detachView()
    }
    /**
     * 提示用户是否保存信息
     */
    private fun tipUserSaveInfo(){
        if(userHeadImg != userNewHeadImg || nickName != editNickName.text.toString().trim() || realName != editRealName.text.toString().trim() || sex != editUserSex.text.toString().trim() || userEmail != editEmail.text.toString().trim() || userCompanyName != editCompanyName.text.toString().trim()){
            MessageDialog.show(this,"提示","用户信息已经修改，是否保存用户信息？","立即保存","暂不保存").setOnOkButtonClickListener { _, _ ->
                personalInformationPresenterImp.uploadUserHeadImg(this@PersonalInformationActivity,userNewHeadImg)
                true
            }.setOnCancelButtonClickListener { _, _ ->
                ActivityUtils.finishActivity(this)
                true
            }
        }else{
            ActivityUtils.finishActivity(this@PersonalInformationActivity)
        }
    }

    /**
     * 展示用户选择头像方式的底部对话框
     */
    private fun showChooseHeadImgBottomSheet(){
        BottomMenu.show(this@PersonalInformationActivity,arrayOf("相册", "拍照")) { text, index ->
            //返回参数 text 即菜单名称，index 即菜单索引
            if(index == 0){
                PictureSelectorUtils.openGallery(this)
            }else{
                PictureSelectorUtils.openCamera(this)
            }
        }
    }

    /**
     * 展示用户选择头像方式的底部对话框
     */
    private fun showChooseSexBottomSheet(){
        BottomMenu.show(this@PersonalInformationActivity, arrayOf("男", "女")) { text, index ->
            //返回参数 text 即菜单名称，index 即菜单索引
            editUserSex.setTextColor(ColorUtils.getColor(R.color.colorAccent))
            editUserSex.text = Editable.Factory.getInstance().newEditable(text)
        }
    }

    override fun uploadHeadImgSuccess(headImgUrl: String?) {
        if(headImgUrl != null){
            GlideUtils.loadImage(superTextHeadImg,"${UrlConstants.baseUrl}${headImgUrl}",superTextHeadImg)
            personalInformationPresenterImp.updateUserInfo(this@PersonalInformationActivity,editNickName.text.toString().trim(),editRealName.text.toString().trim(),editUserSex.text.toString().trim(),editEmail.text.toString().trim(),editCompanyName.text.toString().trim())
        }
    }

    override fun uploadHeadImgFailed() {
        personalInformationPresenterImp.updateUserInfo(this@PersonalInformationActivity,editNickName.text.toString().trim(),editRealName.text.toString().trim(),editUserSex.text.toString().trim(),editEmail.text.toString().trim(),editCompanyName.text.toString().trim())
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            when (requestCode) {
                PictureConfig.CHOOSE_REQUEST -> {
                    // 图片、视频、音频选择结果回调
                    val selectList = PictureSelector.obtainMultipleResult(data)
                    LogUtils.d("selectList",selectList)
                    if(selectList.size >= 1){
                        val localMedia = selectList[0]
                        LogUtils.d("localMedia",localMedia)
                        userNewHeadImg = localMedia.compressPath
                        GlideUtils.loadImage(superTextHeadImg,localMedia.compressPath,superTextHeadImg)
                    }
                    // 例如 LocalMedia 里面返回四种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true  注意：音视频除外
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true  注意：音视频除外
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                    // 4.media.getAndroidQToPath();为Android Q版本特有返回的字段，此字段有值就用来做上传使用
                }
            }
        }
    }

    /**
     * 个人资料获取成功
     */
    override fun personalInfoGetSuccess(personalInfoBean: PersonalInfoBean?) {
        if(personalInfoBean != null){

            userHeadImg = personalInfoBean.face
            userNewHeadImg = userHeadImg

            GlideUtils.loadHeadImg(superTextHeadImg,"${UrlConstants.baseUrl}${userHeadImg}",superTextHeadImg)

            editNickName.setText(personalInfoBean.nickname)
            nickName = personalInfoBean.nickname

            textUserName.text = personalInfoBean.username
            username = personalInfoBean.username

            if(personalInfoBean.name == ""){
                editRealName.setTextColor(ColorUtils.getColor(R.color.colorAccent))
            }else{
                editRealName.setTextColor(ColorUtils.getColor(R.color.colorAccent))
            }
            editRealName.setText(personalInfoBean.name)
            realName = personalInfoBean.name

            if(personalInfoBean.sex == ""){
                editUserSex.setTextColor(ColorUtils.getColor(R.color.secondary_text_color))
                editUserSex.text = "请添加性别信息"
                sex = "请添加性别信息"
            }else{
                editUserSex.setTextColor(ColorUtils.getColor(R.color.colorAccent))
                editUserSex.text = personalInfoBean.sex
                sex = personalInfoBean.sex
            }
            textPhoneNumber.text = personalInfoBean.mobile

            editEmail.setText(personalInfoBean.email)
            userEmail = personalInfoBean.email

            editCompanyName.setText(personalInfoBean.company)
            userCompanyName = personalInfoBean.company
        }
    }

}
